/*******************************************************************************
 * The MOSES project, model based software engineering of networked embedded systems.
 * 
 * Copyright (C) 2010-2013, University of Applied Sciences Wildau,
 * Telematics Research Group, http://www.tm.th-wildau.de/research-group
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 * 
 * Contributors:
 *     University of Applied Sciences Wildau - initial API and implementation
 * 
 * If you are interested in a commercial license please contact us via 
 * e-mail: ralf.vandenhouten@th-wildau.de.
 ******************************************************************************/
package de.thwildau.tm.moses.avro.ui.builder;

import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import javax.inject.Inject;

import org.apache.avro.AvroRuntimeException;
import org.apache.avro.Schema;
import org.apache.avro.compiler.specific.SpecificCompiler;
import org.apache.avro.generic.GenericData.StringType;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.statushandlers.StatusManager;
import org.osgi.framework.Bundle;

import de.thwildau.tm.moses.avro.ui.Activator;
import de.thwildau.tm.moses.avro.ui.preferences.PreferenceConstants;
import de.thwildau.tm.moses.common.builder.IProcessExecutor;
import de.thwildau.tm.moses.common.builder.IProcessExecutor.ResultHandler;
import de.thwildau.tm.moses.common.builder.IProcessExecutor.ResultType;

/**
 * This is a Task class to compile an Avro file. This class has similar functionality than
 * {@link org.apache.avro.compiler.specific.SchemaTask} except it is not Ant-Task.
 * 
 * @author Thomas Kistel
 * @version $Revision: 766 $
 */
public class AvroSchemaCompilerTask implements AvroCompilerTask {
    
    private static final String COMPILER_EXE = "avrogencpp.exe";
    private static final String COMPILER_DLL = "boost_program_options-vc100-mt-1_54.dll";
    private static final String CPP_HEADER_FILE_EXTENSION = "hh";

    private StringType stringType = StringType.CharSequence;
    
    @Inject
    private IProcessExecutor processExecutor;
    
    /**
     * Default Konstruktor.
     */
    public AvroSchemaCompilerTask() {
    }

    /* (non-Javadoc)
     * @see de.thwildau.tm.moses.avro.ui.builder.AvroCompilerTask#doCompile(java.io.File, java.io.File)
     */
    @Override
    public void doCompile(File src, File destDir) throws CoreException {
        Schema.Parser parser = new Schema.Parser();
        try {
            Schema schema = parser.parse(src);
            String namespace = schema.getNamespace() != null ? schema.getNamespace() : "schema";
            
            IPreferenceStore prefStore = Activator.getInstance().getPreferenceStore();
            if(prefStore.getBoolean(PreferenceConstants.PREF_KEY_COMPILE_JAVA)) {
                compileSchemaToJava(src, destDir, schema);
            } 
            
            if(prefStore.getBoolean(PreferenceConstants.PREF_KEY_COMPILE_CPP)) {
                compileSchemaToCpp(src, destDir, namespace);
            }
            
        } catch (EOFException e) {
            throw new CoreException(new Status(IStatus.WARNING, Activator.getBundleId(), "Unexpected end of file. The file " + src.getName() + " may not contain any schema rules.", e));
        } catch (AvroRuntimeException e) {
            throw new CoreException(new Status(IStatus.WARNING, Activator.getBundleId(), "Could not parse schema file " + src.getName(), e));
        } catch (IOException e) {
            throw new CoreException(new Status(IStatus.ERROR, Activator.getBundleId(), "Unexpected I/O error when processing schema file " + src.getName(), e));
        } catch (Exception e) {
            throw new CoreException(new Status(IStatus.ERROR, Activator.getBundleId(), "Unexpected error when processing schema file " + src.getName(), e));
        }
    }

    public StringType getStringType() {
        return stringType;
    }

    public void setStringType(StringType type) {
        this.stringType = type;
    }
    
    public void compileSchemaToJava(File src, File destDir, Schema schema) throws IOException {
        SpecificCompiler compiler = new SpecificCompiler(schema);
        compiler.setStringType(getStringType());
        compiler.compileToDestination(src, destDir);
    }
    
    public void compileSchemaToCpp(File schemaFile, File destDir, String namespace) throws IOException {
        File hhFile = getCppHeaderFile(schemaFile, destDir, namespace);
        String compilerPath = getCompilerPath();
        StringBuilder buf = new StringBuilder();
        buf.append(compilerPath);
        buf.append(" -i ");
        buf.append(schemaFile.getAbsolutePath());
        buf.append(" -o ");
        buf.append(hhFile.getAbsolutePath());
        if(namespace != null && !namespace.isEmpty()) {
            buf.append(" -n ");
            buf.append(namespace);
        }
        String command = buf.toString();
        processExecutor.execCommand(command, new ResultHandler.Stub() {
            
            @Override
            public void onFinishedWithErrors(List<String> resultLines) {
                String result = toSingleString(resultLines);
                if(result != null) {
                    String msg = "SchemaCompiler: The compilation with the C++ compiler finished with errors. Details: " + System.lineSeparator() + result;
                    Activator.logError(msg, null);
                    IStatus status = Activator.toStatus(IStatus.ERROR, msg, null);
                    StatusManager.getManager().handle(status);
                }
            }

            @Override
            public void onFinished(List<String> resultLines) {
                String result = toSingleString(resultLines);
                String message = "C++ compilation successful finished." + (result != null ? "Details: " + result : "");
                Activator.debugInfo(message);
            }
        }, ResultType.INPUT_STREAM, ResultType.ERROR_STREAM);
    }
    
    private String toSingleString(List<String> lines) {
        if(lines.size() == 0)
            return null;
        StringBuilder buf = new StringBuilder();
        for(String line : lines) {
            buf.append(line);
            buf.append(System.lineSeparator());
        }
        return buf.toString();
    }
    
    private File getCppHeaderFile(File schemaFile, File destDir, String namespace) throws IOException {
        String schemaFileName = schemaFile.getName();
        int index = schemaFileName.lastIndexOf(".");
        if(index > 0) {
            schemaFileName = schemaFileName.substring(0, index);
        }
        
        String headerFileName = schemaFileName + "." + CPP_HEADER_FILE_EXTENSION;
        if(Activator.getInstance().getPreferenceStore().getBoolean(PreferenceConstants.PREF_KEY_CREATE_SUBDIR_FOR_CPP_NAMESPACE)) {
            if(namespace != null && !namespace.isEmpty()) {
                String subPath = namespace.replace(".", "/");
                File subDir = new File(destDir, subPath);
                if(!subDir.exists()) {
                    boolean success = subDir.mkdirs();
                    if(!success) {
                        String msg = "SchemaCompiler: Failed to create the subdirectories for the namespace " + namespace;
                        throw new IOException(msg);
                    }
                }
                return new File(subDir, headerFileName);
            }
        }
        return new File(destDir, headerFileName);
    }
    
    private String getCompilerPath() throws IOException {
        Bundle bundle = Activator.getInstance().getBundle();
        IPath exePath = new Path("lib/native/win32/" + COMPILER_EXE);
        IPath ddlPath = new Path("lib/native/win32/" + COMPILER_DLL);
        // locate the dll file. This method-call copy both files into the same dir
        // Therefore the exe-file should find the linked dll
        FileLocator.toFileURL(FileLocator.find(bundle, ddlPath, null));
        
        // we do the same with the exe file and return the path
        URL fileURL = FileLocator.toFileURL(FileLocator.find(bundle, exePath, null));
        String filePath = fileURL.getPath();
        if(filePath.startsWith("/")) {
            filePath = filePath.substring(1);
        }
        return filePath;
    }
}
